<template>
    <div class="textBox">
      <i class="iconfont icon-gonggao1"></i>
      <transition name="slide" mode="out-in">
        <a class="text skip"
           v-if="currentNotice.link"
           :key="currentNotice.id"
           @mouseenter="stopMove"
           @mouseleave="startMove"
           :href="currentNotice.link" target="_blank">{{currentNotice.content}}</a>
        <a class="text no-skip"
           v-else
           :key="currentNotice.id"
           @mouseenter="stopMove"
           @mouseleave="startMove">{{currentNotice.content}}</a>
      </transition>
    </div>
</template>

<script>

  export default {
    name: 'Notice',
    data () {
      return {
        currentIndex: 0,
        timer: null,
        currentNotice: {
          id: 0,
          href: '',
          content: '',
        } // 当前显示的公告
      }
    },
    props: {
      noticeData: {
        type: Array,
        default: function() {
          return [{content: '暂时没有公告'}]
        }
      }
    },
    watch: {
      // 当currentIndex发生变化时，用noticeData中相应的公告对象给currentNotice赋值
      currentIndex: function(newVal) {
        this.currentNotice = this.noticeData[newVal];
      },
      // 当noticeData发生变化时，currentIndex要回到0，避免数组越界；并且要将noticeData中的第一个公告对象赋值给currentNotice，让它正常显示
      noticeData: {
        deep: true,
        handler() {
          this.currentIndex = 0;
          this.currentNotice = this.noticeData[this.currentIndex];
        }
      }
    },
    mounted () {
      // 1.打开定时器
      this.startMove();
    },
    methods: {
      startMove () {
        this.timer = setTimeout(() => {
          if (this.currentIndex === this.noticeData.length - 1) {
            this.currentIndex = 0;
          } else {
            this.currentIndex += 1;
          }
          this.startMove();
        }, 5000);
      },
      stopMove() {
        clearInterval(this.timer);
      },

    }
  }
</script>

<style scoped>
  .textBox {
    width: 70%;
    height: 40px;
    overflow: hidden;
    position: relative;
    z-index: 502;
  }
  .textBox i {
    display: inline-block;
    margin-top: 4px;
    font-size: 24px;
    margin-left: 25px;
    margin-right: 20px;
    font-weight: bold;
  }
  .text {
    width: 100%;
    position: absolute;
    bottom: 15px;
    font-size: 14px;
    cursor: pointer;
  }
  .skip:hover {
    text-decoration: underline;
    color: #409EFF;
  }
  .no-skip {
    cursor: default;
  }
  .slide-enter-active, .slide-leave-active {
    transition: all 0.2s linear;
  }
  .slide-enter{
    transform: translateY(5px);
    opacity: 1;
  }
  .slide-leave-to {
    transform: translateY(-5px);
    opacity: 0;
  }
</style>